#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifndef TEST
	#define IN_FILE_PATH "/var/log/kern.log"
#else
	#define IN_FILE_PATH "test.in"
#endif

#define BUFF_SIZE 2000
#define KEY_WORD "OSLFW:"
#define ACCEPTED "accepted"
#define DENIED "denied"

/*I/O files*/
static FILE* input = NULL;
static FILE* output = NULL;

/**
 * main() - the function prints FW reports for user in input file
 *
 * Parameters:
 * argc - number of input parameters	
 * argv - input parameters
 * 
 * The function
 *			Parses the /var/log/kern.log file.
 *			Creates/opens file that was passed by consule.
 *			Reads all firewall reports for user in /var/log/kern.log.
 *			Prints them to the input file.
 */
int main(int argc, char* argv[])
{
	char str[BUFF_SIZE];
	char* ptr;
	int offset;
	int ses_count = 0, acc_ses_count = 0, den_ses_count = 0;

	/* Check of input parameters */
	if(argc != 2) 
	{
		printf("Error in arguments.\n");
		return 1;
	}
	
	/* Files openning */
	input =  fopen(IN_FILE_PATH, "r");
	output = fopen(argv[1], "w");
				
	if((NULL == input) || (NULL == output))
	{
		printf("Some system error\n");
		return 1;
	}

	/* File reading line by line */
	while(!feof(input))
	{
		fgets(str, BUFF_SIZE, input);

		/* Check if the line is the report for user */
		if((NULL != str) && 
		   (NULL != (ptr = strstr((const char*) str, KEY_WORD))))
		{
			/* Statistics */
			ses_count++;		
			if(NULL != strstr((const char*) str, ACCEPTED))
			{
				acc_ses_count++;
			}
			
			if(NULL != strstr((const char*) str, DENIED))
			{
				den_ses_count++;
			}
			
			/* Delete special identifier from the report to user */
			offset = ptr - str;
			
			str[offset] = '\0';
			fputs((const char*)str, output);
			offset += sizeof(KEY_WORD);

			/* Writing reports to the user file */
			fputs((const char*)&str[offset-1], output);						
		}
	}
	
	/* Writing statistics to the user file */
	sprintf(str, "%d sessions were started: \n	%d sessions were accepted by ipcontext.\n	%d sessions were denied by ipcontext. \n", ses_count, acc_ses_count, den_ses_count);
	fputs(str, output);

	/* Files closing */
	fclose(input);
	fclose(output);

	return 0;
}
